<?php
/**
 *
 * This module is used to initialize a session when being called with 
 * POST parameters, and to end the session when being called with a 
 * GET parameter 'logout'.
 *
 * It accepts two parameters in POST method: `uid' refers to the 
 * userid in the database, and `upass' is the password in base64 form.
 *
 * And then, it determines whether the user's login is successful. If 
 * it is OK, then initializes a session, and stores the CustomerNum as 
 * 'unum' into the session. Finally, sets the user name as a cookie 
 * 'uname'. If the login failed, it does nothing.
 *
 * @author Zhihao Yuan
 * @version 0.4
 * @package dummy-auto
 * @todo
 *
 */

include("config.inc");
include("app/dummy-app.inc");

if (!isset($_POST['role']) or $_POST['role'] == 'user') {

if ($_POST['logout'] == 'yes') {
	session_start();
	session_end();
	set_session_cookie('uname', '');
	exit;
}

$user = mysql_fetch_assoc(mysql_query("select Name, CustomerNum 
	from Login_Info left join Customer using(CustomerNum) 
	where ID = '$_POST[uid]' and Passwd = '$_POST[upass]'"));
if ($user) {
	session_start();
	$_SESSION['unum'] = $user['CustomerNum'];
	set_session_cookie('uname', $user['Name']);
}

} elseif ($_POST['role'] == 'employee') {

if ($_POST['logout'] == 'yes') {
	session_start();
	session_end();
	set_session_cookie('ename', '');
	exit;
}

$user = mysql_fetch_assoc(mysql_query("select Name, EmpID 
	from Employee 
	where EmpID = '$_POST[eid]' and Passwd = '$_POST[epass]'"));
if ($user) {
	session_start();
	$_SESSION['empid'] = $user['EmpID'];
	set_session_cookie('ename', $user['Name']);
}

} else exit_404('Unknown login role');
?>
